package at.codebase.web.servlets.ajax;

import java.util.ArrayList;

import org.json.simple.JSONObject;

import at.codebase.core.search.ItemSearch;
import at.codebase.core.search.ItemSearchResult;
import at.codebase.core.search.ItemSearchResultInfo;
import at.codebase.security.SecurityUtils;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterDoesNotExistException;
import at.codebase.web.util.servlet.SecureServlet;

import com.google.appengine.api.search.SearchQueryException;
import com.google.appengine.labs.repackaged.org.json.JSONArray;

/**
 * @author Daniel Marth <danielmarth@gmx.at>
 */
public class AjaxItemSearchProvider extends SecureServlet {

	private final static int MAX_RESULTS = 10;

	@Override
	protected RequestType requestType() {
		return RequestType.POST_AND_GET;
	}

	@Override
	protected void initSecurityLevels(ArrayList<UserLevel> secLevels) {
		secLevels.add(UserLevel.ANONYMOUS);
		secLevels.add(UserLevel.REGISTERED);
		secLevels.add(UserLevel.ADMIN);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void processRequestSecurityLevel(RequestInformation requestInfo,
			UserLevel level, RequestType requestType) {
		String query = "";
		try {
			query = requestInfo.getParameters().getString("term");
		} catch (ParameterDoesNotExistException e) {
		}
		query =  "titleSubstrings:"+SecurityUtils.sanatizeSearchQuery(query);

		ItemSearchResultInfo resultList = null;
		try {
			resultList = ItemSearch.search(query, MAX_RESULTS, 0);
		} catch (SearchQueryException ex) {
			// ignore invalid search expressions which mostly occur while typing
			return;
		}

		JSONArray jsonList = new JSONArray();
		for (ItemSearchResult result : resultList.getResults()) {
			JSONObject resultJsonObject = new JSONObject();
			resultJsonObject.put("id", result.getItem().getId().toString());
			resultJsonObject.put("label",
					SecurityUtils.sanatize(result.getItem().getTitle()));
			if (!(requestInfo.isUserLoggedIn() && result.getItem().getId()
					.equals(requestInfo.getUser().getId())))
				jsonList.put(resultJsonObject);
		}
		writer().printInsecure(jsonList.toString());
	}
}
